﻿package  {
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	//TODO: take into account, that we must have access with mask 2
	
	public class PlayerPanel extends MovieClip {
		private var friendNumber: Number = 0;
		static private var timer: Timer = new Timer(400);
		
		private var main: Main = null;
		static private var friends: Array = new Array();	//Friends, who installed application
		
		static private const PROFILES_LOADED = "profilesLoaded";
		static private var profilesLoadedNotificator: EventDispatcher = new EventDispatcher();
		
		static private var currentNumber: Number = 0;
		public function PlayerPanel() {
			// constructor code
			friendNumber = currentNumber;
			currentNumber ++;
			main = Main(root);
			
			if(friendNumber == 0)
				main.addEventListener (Event.ADDED_TO_STAGE, onAddedToStage);
			profilesLoadedNotificator.addEventListener(PlayerPanel.PROFILES_LOADED, onProfilesLoaded);
		}
		
		/*It loads friends, which installed application */
		private function onAddedToStage(e: Event): void {
			main.vKontakte.api("friends.getAppUsers", {}, loadFriendList, vkFail);
		}
		
		private function centreImage(e: Event): void {
			var loader: Loader = e.currentTarget.loader as Loader;
			loader.x = -loader.width / 2;
			loader.y = -loader.height / 2;
		}
		private function onProfilesLoaded(e: Event): void {
			if (friendNumber >= friends.length) {
				addEventListener(MouseEvent.CLICK, onClick);
				buttonMode = true;
				nameLabel.text = "Пригласить"
				surnameLabel.text = "друга"
				scoresLabel.text = " ";
				return;
			}
			var photo: Loader = new Loader();
			photo.load(new URLRequest( friends[friendNumber].photo));
			photo.contentLoaderInfo.addEventListener(Event.COMPLETE,
				centreImage);
			photoImage.addChild(photo);		
			nameLabel.text = friends[friendNumber].name;
			surnameLabel.text = friends[friendNumber].surname;
			scoresLabel.text = friends[friendNumber].scores;
		}
		
		private function onClick(e: MouseEvent): void {
			if (!main.localWork)
				main.vKontakte.callMethod("showInviteBox");
		}
		private var numReceivedProfiles: Number = 0;
		private function onProfileReceived(e: Event) {
			
			numReceivedProfiles ++;
			trace ("onProfilesReceived", friends.length, ':', numReceivedProfiles);
			
			if (numReceivedProfiles >= friends.length - 1) {
				friends.sortOn('scores', Array.NUMERIC);
				friends.reverse();
				profilesLoadedNotificator.dispatchEvent(new Event(PROFILES_LOADED));
			}
		}
		
		private var scoresQueried = 0;
		private function queryScores(e: TimerEvent):void {
			trace("scoresQueried: ", scoresQueried, ':', friends.length);
			if (scoresQueried >= friends.length) {
				timer.stop();
				dispatchEvent(new Event(PROFILES_LOADED));
				return;
			}
			
			
			friends[scoresQueried].startReceiveScores();
				
			friends[scoresQueried].addEventListener(Gamer.STORES_RECEIVED, onProfileReceived);
			scoresQueried ++;
		}
		
		private function loadFriendsProfiles(e: Object): void {
			for each (var friend in e) {
				var gamer: Gamer = new Gamer(main.vKontakte, friend.uid, friend.first_name, friend.last_name, friend.photo);
				friends.push ( gamer );
				trace("friend.uid = " + gamer.user_id);
			}
			
			timer.addEventListener(TimerEvent.TIMER, queryScores);
			timer.start();
		}
		private function loadFriendList(e: Object):void {
			var listUsers: String = "";	//List of users in string, for sending info to vkontakte
			for each (var a: Number in e as Array) {
				listUsers += a + ", ";
			}
			listUsers += main.viewerID;
			//listUsers = listUsers.substring (0, listUsers.length - 1);
			
			main.vKontakte.api ("getProfiles", 
				{uids: listUsers, fields: "first_name, last_name, photo" }, 
				loadFriendsProfiles,
				vkFail);
		}
		
		private function vkFail(e: Object):void {
			trace("Fail" + e.response);
		}
		
	}
	
}
